from sqlalchemy import Boolean, Column, Integer, String, Float, Text, ForeignKey, Enum, DateTime
from sqlalchemy.orm import relationship
from datetime import datetime
from app.db.base_class import Base
import enum

class LogisticsStatus(enum.Enum):
    pending = "pending"           # 待发货
    processing = "processing"     # 处理中
    shipping = "shipping"         # 运输中
    delivered = "delivered"       # 已送达
    returned = "returned"         # 已退回

class Warehouse(Base):
    __tablename__ = "warehouses"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    address = Column(String(255), nullable=False)
    contact_name = Column(String(100))
    contact_phone = Column(String(20))
    is_active = Column(Boolean, default=True)

class LogisticsProvider(Base):
    __tablename__ = "logistics_providers"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    code = Column(String(50), unique=True)  # 物流公司代码
    tracking_url = Column(String(255))      # 物流追踪URL模板
    api_config = Column(Text)               # API配置信息(JSON格式)
    is_active = Column(Boolean, default=True)

class ShipmentRecord(Base):
    __tablename__ = "shipment_records"

    id = Column(Integer, primary_key=True, index=True)
    order_id = Column(Integer, ForeignKey("orders.id"))
    warehouse_id = Column(Integer, ForeignKey("warehouses.id"))
    provider_id = Column(Integer, ForeignKey("logistics_providers.id"))
    tracking_number = Column(String(100))   # 物流单号
    status = Column(Enum(LogisticsStatus), default=LogisticsStatus.pending)
    shipping_fee = Column(Float, default=0.0)
    estimated_delivery = Column(DateTime)    # 预计送达时间
    actual_delivery = Column(DateTime)      # 实际送达时间
    remark = Column(Text)

    # 关联
    order = relationship("Order")
    warehouse = relationship("Warehouse")
    provider = relationship("LogisticsProvider")
    tracking_info = relationship("TrackingInfo", back_populates="shipment")

class TrackingInfo(Base):
    __tablename__ = "tracking_info"

    id = Column(Integer, primary_key=True, index=True)
    shipment_id = Column(Integer, ForeignKey("shipment_records.id"))
    location = Column(String(255))          # 当前位置
    status = Column(String(100))            # 物流状态
    description = Column(Text)              # 状态描述
    occurred_at = Column(DateTime)          # 发生时间

    # 关联
    shipment = relationship("ShipmentRecord", back_populates="tracking_info")